import os
import json
from pathlib import Path


def builder():
    
    #建立全局字典 -> tbl
    tbl = {'level':{}}          #保存难度对应标识
    reWrite = '0'           #当存在文件时覆盖[Y]还是追加[N]

    with open('default.json','r',encoding = 'UTF-8') as j:          #载入default.json -> mob
        mob = json.load(j)

        _CONFIG_PATH = Path('Configs/' + mob['name']+'/config.json')          #设置config.json所在路径
        if _CONFIG_PATH.exists() == False:          #文件不存在就创建一个
            Path('Configs/' + mob['name']).mkdir(parents=True)
            _CONFIG_PATH.touch()
        else:
            while (reWrite in ['N','Y']) == False:          #文件存在时是覆盖[Y]还是追加[N]
                reWrite = input( "检测到已存在相应config，覆盖[Y]还是追加[N]？")

        
        with open(_CONFIG_PATH,'r',encoding = 'UTF-8') as k:           #载入config.json -> ncd
            ncd = json.load(k) if os.path.getsize(_CONFIG_PATH) !=0 else {}         #如果json文件为空，使用空字典

            #保存难度对应标识
            for csong in mob['folder']:
                if reWrite == 'N' and ncd['level'].get(csong['name'],False):         #追加模式且原本存在键
                    tbl['level'][csong['name']] = ncd['level'][csong['name']]        
                else:       #覆盖模式或追加模式下不存在键
                    tbl['level'][csong['name']] = input("请输入  " + csong["name"] + "  对应的难度：") 

            #输入难度表符号及难度表名
            tbl['icon'] = ncd['icon'] if (ncd.get('icon',False) and reWrite == 'N') else input("难易度表符号：")
            tbl['name'] = ncd['name'] if (ncd.get('name',False) and reWrite == 'N') else input("输入难易度表名：")
            
        with open(_CONFIG_PATH,'w',encoding = 'UTF-8') as f:           #写入config.json
            json.dump(tbl,f,ensure_ascii = False)

if __name__ == '__main__':           #检测是否独立运行
    builder()
